<template>
  <div id="main">
    <!--<div class="left">-->
    <!--<div class="nav-list-box">-->
    <!--<div class="nav-list-item" :class="active == index?'nav-list-item-active':''" v-for="(item,index) in navList"-->
    <!--:key="index" @click="getNav(item,index)">-->
    <!--{{ item.name }}-->
    <!--</div>-->
    <!--</div>-->
    <!--</div>-->
    <div class="content" id="playWnd">

    </div>
  </div>
</template>

<script>
  function debounce(fn, interval) {  //防抖
    var timer
    var gapTime = interval || 1000
    return function () {
      clearTimeout(timer)
      var context = this
      let args = arguments[0]
      timer = setTimeout(function () {
        fn.call(context, ...arguments)
      }, gapTime)
    }
  }

  function throttle(fn, interval) {
    console.log(565656)
    var enterTime = 0
    var gapTime = interval || 300
    return function () {
      var context = this
      var backTime = new Date()
      if (backTime - enterTime > gapTime) {
        fn.call(context, ...arguments)
        enterTime = backTime
      }
    }
  }

  var oWebControl = null;
  var bIE = (!!window.ActiveXObject || 'ActiveXObject' in window);// 是否为IE浏览器
  var pubKey = '';                  // demo中未使用加密，可根据需求参照开发指南自行使用加密功能
  var initCount = 0;                // 异常重启计数
  var iframePos = {};               // iframe相对文档的位置
  var parentTitle = '';	          // 父页面标题
  var iframeClientPos = null;       // iframe相对视窗的位置
  var iframeParentShowSize = null;  // 视窗大小 width height
  var isLoadingOut = false;  // 视窗大小 width height

  var isControl = false;  // 初始化完成
  var isSend = false;  // 数据传输完成

  export default {
    data() {
      return {
        indexCode:[],
        show_type:'2x2',
        receivedMessage: '',
        navList: [
          {
            name: '大厅门',
            value: 'a7adfcd0ceb94561aac2b9c2c65f6331'
          },
          {
            name: '五楼通道西南角',
            value: 'dd2198817aaf4f83abfc36ce30e2e89d'
          },
          {
            name: '四楼通道西北角',
            value: 'c8ddecc12cd046f080bae316e86c59de'
          },
          {
            name: '四楼通道东北角',
            value: '6415dc72b0b64fbaad5292a47b9a2149'
          },
        ],
        active: -1,
        endTime : Math.floor(new Date(this.dateFormat(new Date(), "yyyy-MM-dd 23:59:59").replace('-', '/').replace('-', '/')).getTime() / 1000).toString(),
        startTime : Math.floor(new Date(this.dateFormat(new Date(), "yyyy-MM-dd 00:00:00").replace('-', '/').replace('-', '/')).getTime() / 1000).toString(),
        playTime : Math.floor(new Date(this.dateFormat(new Date(), "yyyy-MM-dd 00:00:00").replace('-', '/').replace('-', '/')).getTime() / 1000).toString(),
      }
    },
    watch: {},
    created() {
      this.initPlugin();
    },
    mounted() {
      window.addEventListener('message', this.handleMessage);
      window.myCloseVideo = () => {
        console.log('destruction接收')
        oWebControl.JS_HideWnd();  // 先让窗口隐藏，规避可能的插件窗口滞后于浏览器消失问题
        oWebControl.JS_DestroyWnd().then(function(){},function(){});
      };
      // this.getQueryParams()
    },
    destroyed() {
    },
    beforeDestroy() {
      console.log('销毁iframe')
      if (oWebControl != null) {
        oWebControl.JS_HideWnd();  // 先让窗口隐藏，规避可能的插件窗口滞后于浏览器消失问题
        oWebControl.JS_Disconnect().then(function () {
        }, function () {
        });
      }
      window.removeEventListener('message', this.handleMessage);

    },
    methods: {
      handleMessage(e) {
        console.log(777777,e)
        if(e && e.data){
          console.log(777777,e.data.action)
          switch (e.data.action){
            case 'sendTitle':              // 父页面将其标题发送过来，子页面保存该标题，以便创建插件窗口成功后将标题设置回给父页面
              parentTitle = e.data.info;
              break;
            case 'updateInitParam':              // 更新插件位置
              iframePos = e.data.iframeClientPos
              iframeParentShowSize = e.data.showSize;
              isSend = true
              if(isControl){
                this.init();
              }
              break;
            case 'scroll':
              iframeParentShowSize = e.data.showSize;   // 视窗大小
              iframePos = e.data.iframeClientPos;          // iframe与文档的偏移量
              iframeClientPos = e.data.iframeClientPos; // iframe相对视窗的位置
              var scrollValue = e.data.scrollValue;     // 滚动条滚动偏移量
              if(oWebControl){
                oWebControl.JS_SetDocOffset({
                  left: iframePos.left + scrollValue.left,
                  top: iframePos.top + scrollValue.top
                });    // 更新插件窗口位置
              }
              break;
            case 'updateCode':
              this.indexCode = e.data.code;
              console.log(7777,this.indexCode)
              if (isLoadingOut) {
                this.getImplement()
              }

              window.addEventListener('resize', () => {
                if (oWebControl != null) {
                }
              });
              break;
            case 'destruction':
              oWebControl.JS_HideWnd();  // 先让窗口隐藏，规避可能的插件窗口滞后于浏览器消失问题
              oWebControl.JS_DestroyWnd().then(function(){},function(){});
              break;
            default:
              break;
            }
        }
      },

      getImplement(){
        $http.get('videoApi',{
          code: this.indexCode,
        }).then(res => {
        let camerCode = res.data;
        if(camerCode.length > 0){
            for (let i = 0; i < camerCode.length; i++){
              console.log('分割code',camerCode[i])
              this.requestInterface(camerCode[i])
            }
          }
        })
      },

      initPlugin() {
        let that = this;
        oWebControl = new WebControl({
          szPluginContainer: "playWnd",
          iServicePortStart: 15900,
          iServicePortEnd: 15900,
          szClassId: "23BF3B0A-2C56-4D97-9C03-0CB103AA8F11",   // 用于IE10使用ActiveX的clsid
          cbConnectSuccess: ()=> {
          initCount = 0;
        this.setCallbacks();
        oWebControl.JS_StartService("window", {
          dllPath: "./VideoPluginConnect.dll"
        }).then(()=> {
          oWebControl.JS_CreateWnd("playWnd", 800, 400).then(function () {
          console.log("JS_CreateWnd success");
          oWebControl.JS_RequestInterface({
            funcName: "getRSAPubKey",
            argument: JSON.stringify({
              keyLength: 1024
            })
          }).then((oData)=> {
            console.log(oData)
          isControl = true
          if(isControl){
            that.init();
          }
          if (oData.responseMsg.data) {
            pubKey = oData.responseMsg.data


          }
        });
        });
      }, function () {

        });
      },
        cbConnectError: ()=>{
          console.log("cbConnectError");
          oWebControl = null;
          $("#playWnd").html("插件未启动，正在尝试启动，请稍候...");
          WebControl.JS_WakeUp("VideoWebPlugin://");
          initCount++;
          if (initCount < 3) {
            setTimeout( ()=> {
              this.initPlugin();
          }, 3000)
          } else {
            $("#playWnd").html("插件启动失败，请检查插件是否安装！");
          }
        },
        cbConnectClose: (bNormalClose)=> {
          // 异常断开：bNormalClose = false
          // JS_Disconnect正常断开：bNormalClose = true
          console.log("cbConnectClose");
          oWebControl = null;
          $("#playWnd").html("插件未启动，正在尝试启动，请稍候...");
          WebControl.JS_WakeUp("VideoWebPlugin://");
          initCount++;
          if (initCount < 3) {
            setTimeout(()=> {
              this.initPlugin();
          }, 3000)
          } else {
            $("#playWnd").html("插件启动失败，请检查插件是否安装！");
          }
        }
      });

      },
      init() {
        //param = {
        //
        //}
        let that = this;
        console.log(11111,oWebControl)
        let JsonParam = {
          "argument": '{"appkey": "20124682","ip": "172.139.0.194","port": 443,"secret": "vWF3o9ts58FzVswsejcH","enableHTTPS": 1,"language": "zh_CN","layout":"2x2","playMode": 1,"reconnectDuration": 5,"reconnectTimes": 5,"showSmart": 0,"showToolbar": 1,"snapDir": "D:/snap","videoDir": "D:/video"}',
          "funcName": "init"
        }
        JsonParam.argument = JSON.parse(JsonParam.argument);
        JsonParam.argument.layout = this.show_type;
        JsonParam.argument = JSON.stringify(JsonParam.argument);

        oWebControl.JS_RequestInterface(JsonParam).then(function (oData) {
          console.log(11111,oData)
          console.log(JSON.stringify(oData ? oData.responseMsg : ''));
          oWebControl.JS_SetDocOffset({
            left: iframePos.left,
            top: iframePos.top
          });  // 更新插件窗口位置

          oWebControl.JS_Resize(iframeParentShowSize.width, iframeParentShowSize.height);
          isLoadingOut = true
          that.getImplement()
        });
      },
      // 设置窗口控制回调
      setCallbacks() {
        oWebControl.JS_SetWindowControlCallback({
          cbIntegrationCallBack: this.cbIntegrationCallBack
        });
      },

      // 推送消息
      cbIntegrationCallBack(oData) {
        console.log(JSON.stringify(oData.responseMsg));
      },

      // RSA加密
      setEncrypt(value) {
        var encrypt = new JSEncrypt();
        encrypt.setPublicKey(pubKey);
        return encrypt.encrypt(value);
      },

      isJSON(str) {
        if (typeof str == 'string') {
          try {
            var obj=JSON.parse(str);
            if(typeof obj == 'object' && obj ){
              return true;
            }else{
              console.log("param is not the correct JSON message");
              return false;
            }
          } catch(e) {
            console.log("param is not the correct JSON message");
            return false;
          }
        }
        console.log('It is not a string!')
      },
      setWndCover() {
        //获取web页面的尺寸
        var iWidth = $(window).width();
        var iHeight = $(window).height();
        //获取播放窗口div元素的左边界、右边界距离web页面左边界的长度、上边界、下边界距离web页面上边界的长度
        var oDivRect = $("#playWnd").get(0).getBoundingClientRect();
        //Math.round 为四舍五入    Math.abs 为取绝对值
        var iCoverLeft = (oDivRect.left < 0) ? Math.abs(oDivRect.left): 0;
        var iCoverTop = (oDivRect.top < 0) ? Math.abs(oDivRect.top): 0;
        var iCoverRight = (oDivRect.right - iWidth > 0) ? Math.round(oDivRect.right - iWidth) : 0;
        var iCoverBottom = (oDivRect.bottom - iHeight > 0) ? Math.round(oDivRect.bottom - iHeight) : 0;

        iCoverLeft = (iCoverLeft > 800) ? 800 : iCoverLeft;
        iCoverTop = (iCoverTop > 400) ? 400 : iCoverTop;
        iCoverRight = (iCoverRight > 800) ? 800 : iCoverRight;
        iCoverBottom = (iCoverBottom > 400) ? 400 : iCoverBottom;

        oWebControl.JS_RepairPartWindow(0, 0, 801, 400);  // 多1个像素点防止还原后边界缺失一个像素条
        //抠除左边界
        if (iCoverLeft != 0) {
          oWebControl.JS_CuttingPartWindow(0, 0, iCoverLeft, 401);
        }
        //抠除上边界
        if (iCoverTop != 0) {
          oWebControl.JS_CuttingPartWindow(0, 0, 801, iCoverTop);  // 多剪掉一个像素条，防止出现剪掉一部分窗口后出现一个像素条
        }
        //抠除右边界
        if (iCoverRight != 0) {
          oWebControl.JS_CuttingPartWindow(801 - iCoverRight, 0, iCoverRight, 401);
        }
        //抠除下边界
        if (iCoverBottom != 0) {
          oWebControl.JS_CuttingPartWindow(0, 401 - iCoverBottom, 801, iCoverBottom);
        }
        //弹框示例位置扣除
        if (showDivInstruction)
        {
          // 获取弹框的位置、尺寸信息
          var oDivLightRect = document.getElementById('light').getBoundingClientRect();

          iCoverLeft = (oDivLightRect.left - oDivRect.left < 0) ? 0 : oDivLightRect.left - oDivRect.left;
          iCoverTop = (oDivLightRect.top - oDivRect.top < 0) ? 0 : oDivLightRect.top - oDivRect.top;
          iCoverRight = (oDivLightRect.right - oDivRect.left < 0) ? 0 : oDivLightRect.right - oDivRect.left;
          iCoverBottom = (oDivLightRect.bottom - oDivRect.top < 0) ? 0 : oDivLightRect.bottom - oDivRect.top;

          iCoverLeft = (iCoverLeft > 800) ? 800 : Math.round(iCoverLeft);
          iCoverTop = (iCoverTop > 400) ? 400 : Math.round(iCoverTop);
          iCoverRight = (iCoverRight > 800) ? 800 : Math.round(iCoverRight);
          iCoverBottom = (iCoverBottom > 400) ? 400 : Math.round(iCoverBottom);

          //JS_CuttingPartWindow接口参照开发指南，参数为：抠图左上角点在插件窗口上的left长度、top长度、所扣除矩形区域的宽度、所扣除矩形区域的长度
          oWebControl.JS_CuttingPartWindow(iCoverLeft - 1, iCoverTop - 1, iCoverRight - iCoverLeft + 2, iCoverBottom - iCoverTop + 2);
        }
      },
      dateFormat(oDate, fmt) {
        var o = {
          "M+": oDate.getMonth() + 1, //月份
          "d+": oDate.getDate(), //日
          "h+": oDate.getHours(), //小时
          "m+": oDate.getMinutes(), //分
          "s+": oDate.getSeconds(), //秒
          "q+": Math.floor((oDate.getMonth() + 3) / 3), //季度
          "S": oDate.getMilliseconds()//毫秒
        };
        if (/(y+)/.test(fmt)) {
          fmt = fmt.replace(RegExp.$1, (oDate.getFullYear() + "").substr(4 - RegExp.$1.length));
        }
        for (var k in o) {
          if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
          }
        }
        return fmt;
      },
      //计算缩放比例
      adaptation() {
        var w = document.body.clientWidth;
        var h = document.body.clientHeight;
        var nw = 1920,
          nh = 1080;
        var left, top, scale;
        if (w / h > nw / nh) {
          scale = h / nh;
          top = 0;
          left = (w - nw * scale) / 2;
        } else {
          scale = w / nw;
          left = 0;
          top = (h - nh * scale) / 2;
        }
        document.getElementById('main').setAttribute('style', 'transform: scale(' + scale + ');' + 'top:' + top + 'px;');

      },
      getNav(item, index) {
        if (this.active == index) {
          return
        }
        this.active = index
        this.requestInterface(item.value)
      },

      // value为字符串，JS_RequestInterface仅接收json格式的变量，且需要先解析出argument，并且将argument字段的内容转为字符串
      requestInterface(code) {
        var JsonParam = {
          "argument": {
            "authUuid": "",
            "cameraIndexCode": code,
            "endTimeStamp": "1716307199",
            "ezvizDirect": 0,
            "gpuMode": 0,
            "playTimeStamp": "1716220800",
            "recordLocation": 1,
            "startTimeStamp": "1716220800",
            "transMode": 1,
            "wndId": 0,
            "cascade": 1
          },
          "funcName": "startPlayback"
        };
        var JsonArgument = JsonParam.argument;
        JsonParam.argument = JSON.stringify(JsonArgument);
        console.log(8888,JsonParam)
        oWebControl.JS_RequestInterface(JsonParam).then(function (oData) {
          console.log(oData)
          console.log(JSON.stringify(oData ? oData.responseMsg : ''));
        });
      },
    },
  }
</script>

<style scoped>
  #main {
    display: flex;
    font-family: '黑体';
    box-sizing: border-box;
    width: 100%;
    height: 100vh;
  }

  .left {
    flex-shrink: 0;
    margin: 20px 0px 20px 15px;
    background-color: #fff;
  }

  .content {
    flex: 1;
    height: 100vh;
    box-sizing: border-box;
  }

  .nav-list-box {
    padding: 10px;
  }

  .nav-list-item {
    height: 60px;
    line-height: 60px;
    box-sizing: border-box;
    padding: 0 10px;
    font-size: 18px;
    background-color: #cccccc;
    color: #000000;
    cursor: pointer;
    border-bottom: 1px solid #666666;
  }

  .nav-list-item:hover {
    background-color: #449de2;
  }

  .nav-list-item-active {
    background-color: #0090ff;
    color: #ffffff;
  }

</style>
